<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>发布订阅模式</title>
</head>
<body>
    <script>
        // 事件触发器
        class EventEmitter {
          constructor () {
            // 存储事件对象
            this.subs=Object.create( null )
          }
          // 注册事件
          $on (eventType,handler){
            this.subs[eventType] = this.subs[eventType] || [] // 短路判断，有值赋值无值默认
            this.subs[eventType].push(handler)
          }
          // 触发事件
          $emit (eventType) {
            if (this.subs[eventType]){
              this.subs[eventType].forEach(handler=>{
                handler ()
              })
            }
          }
        }

        // 测试
        let em = new EventEmitter()
        em.$on('click', () => {
          console.log('click1')
        })
        em.$on('click', () => {
          console.log('click2')
        })

        em.$emit('click')
    </script>
</body>
</html>
